package com.core.website.api;

import com.core.website.common.Result;
import com.core.website.common.ResultUtil;
import com.core.website.common.TableDataInfo;
import com.core.website.entity.EditPass;
import com.core.website.entity.User;
import com.core.website.service.UserService;
import com.github.pagehelper.PageHelper;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/userApi")
public class UserApi {
    @Autowired
    private UserService userService;

    @PostMapping("/add")
    public Result register(@RequestBody User user){
        if(StringUtils.isNotEmpty(user.getUserName())){
            User hasUser = userService.findByUserName(user.getUserName());
            if(null!=hasUser&& StringUtils.isNotEmpty(hasUser.getId())){
                return ResultUtil.error(-1,"账号已存在!");
            }
        }
        int result = userService.add(user);
        return ResultUtil.success(result);
    }
    @PostMapping("/queryAll")
    public TableDataInfo queryAll(@RequestBody User user){
        PageHelper.startPage(user.getPageNum(), user.getPageSize());
        List<User> result = userService.queryAll(user);
        return TableDataInfo.getDataTable(result);
    }
    @GetMapping("/queryInfo")
    public Result queryInfo(){
        User subject = (User) SecurityUtils.getSubject().getPrincipal();
        if(null==subject){
           return ResultUtil.error(-1000,"用户未登录");
        }
        User result = userService.queryInfo(subject.getId());
        return ResultUtil.success(result);
    }
    @GetMapping("/queryById")
    public Result queryById(String id){
        User result = userService.queryInfo(id);
        return ResultUtil.success(result);
    }
    @PostMapping("/delete")
    public Result delete(@RequestBody List<String> ids){
        int result=userService.delete(ids);
        return ResultUtil.success(result);
    }
    @PostMapping("/edit")
    public Result edit(@RequestBody User user){
        int result = userService.edit(user);
        return ResultUtil.success(result);
    }
    @PostMapping("/editPass")
    public Result editPass(@RequestBody EditPass editPass){
        User subject = (User) SecurityUtils.getSubject().getPrincipal();
        if(null==subject){
            return ResultUtil.error(-1000,"用户未登录");
        }
        int result = userService.editPass(editPass);
        if(-1==result){
            return ResultUtil.error(-1,"原密码错误!");
        }
        return ResultUtil.success(result);
    }
    @PostMapping("/editPassById")
    public Result editPassById(@RequestBody EditPass editPass){
        int result = userService.editPassById(editPass);
        return ResultUtil.success(result);
    }

}
